package study.distributed.shardingjdbc.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;

@Configuration
public class MasterDataSourceConfig extends BaseDataSourceConfig{


    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.shardingsphere.datasource.ds0")
    public DataSource masterDatasource() {
        return new DruidDataSource();
    }

    @Bean
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier(value = "masterDatasource")  DataSource dataSource, @Qualifier("masterConfiguration") org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setConfiguration(configuration);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/normal/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public org.apache.ibatis.session.Configuration masterConfiguration() {
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        return configuration;
    }

    @Bean(value = MASTER_TRANSACTION_MANAGER)
    @Primary
    public DataSourceTransactionManager masterDataSourceTransactionManager(@Qualifier(value = "masterDatasource")  DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Configuration
    @AutoConfigureAfter(MasterDataSourceConfig.class)
    public static class MybatisMapperConfiguration{

        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer() {
            MapperScannerConfigurer configurer = new MapperScannerConfigurer();
            configurer.setSqlSessionFactoryBeanName("masterSqlSessionFactory");
            configurer.setBasePackage("study.distributed.shardingjdbc.dao.normal");
            return configurer;
        }
    }


}
